class Admin::ProductPropertiesController < Admin::AdminController
  before_filter :load_product
  before_filter :load_property_patterns, :only => [:edit]

  #filter_access_to :all, :additional_collection => {:restructure => :update}

  def show
    redirect_to :action => :edit
  end

  def new_property
    @property = Property.new({
      :property_group_id => @product.property_group.id
    })

    @property.save!(:validate => false)
    
    @property_attribute = PropertyAttribute.new({
      :property_id => @property.id
    })

    @property_attribute.save!(:validate => false)

    respond_to do |format|
      format.js {render :action => "new_property", :layout => false}
    end
  end

  def new_property_attribute
    @property = Property.find(params[:property_id])
    
    @property_attribute = PropertyAttribute.new({
      :property_id => params[:property_id]
    })

    @property_attribute.save!(:validate => false)

    respond_to do |format|
      format.js {render :action => "new_property_attribute", :layout => false}
    end
  end

  def edit
    add_crumb("Správa výrobků", admin_products_path)
    add_crumb("Editace výrobku", edit_admin_product_path(params[:product_id]))
    add_crumb("Vlastnosti")

    @product.property_group || @product.build_property_group
    @product.property_group.properties || @product.property_group.properties.build
    @product.property_group.properties.each do |property|
      property.property_attributes.roots.build
    end
  end

  def add_property_pattern
    @property_pattern = PropertyPattern.find(params[:property_pattern_id])

    respond_to do |format|
      format.js {render :action => :new_property_attribute, :layout => false}
    end
  end

  def update
    if @product.update_attributes(params[:product])
      redirect_to :action => :edit, :notice => "Vlastnosti byly úspěšně uloženy"
    else
      render :action => :edit
    end
  end

  def restructure
    prev_id   = params[:prev_id].to_i unless params[:prev_id].blank?
    next_id   = params[:next_id].to_i unless params[:next_id].blank?
    node_id   = params[:node_id].to_i unless params[:node_id].blank?
    parent_id = params[:parent_id].to_i unless params[:parent_id].blank?

    prev_id ||= 0
    next_id ||= 0
    node_id ||= 0
    parent_id ||= 0

    property_attribute = PropertyAttribute.find(node_id)

    if prev_id.zero? && next_id.zero?
      property_attribute.move_to_child_of parent_id
    elsif !prev_id.zero?
      property_attribute.move_to_right_of prev_id
    elsif !next_id.zero?
      property_attribute.move_to_left_of next_id
    end

    render :nothing => true
  end


  private
  def load_product
    @product = Product.find(params[:product_id])
  end

  def load_property_patterns
    @property_patterns = PropertyPattern.all
  end
end
